<script>
	import Vue from 'vue'
	// #ifdef APP-PLUS
	import APPUpdate from "./js_sdk/zhouWei-APPUpdate/APPUpdate/index.js";
	const jpushModule = uni.requireNativePlugin('JG-JPush');
    import { startServe } from "@/uni_modules/Lin97112479-location"
    import { getLocations,clearLocationsrequestLocation,setBattery } from "@/uni_modules/Lin97112479-location/utssdk/index.js"
	// #endif
	export default {
		onLaunch: function() {
			console.log('App Launch')

			// #ifdef APP-PLUS
			// 设置屏幕常亮  安卓需要<uses-permission android:name="android.permission.WAKE_LOCK"/>权限，需要重新打包。苹果不用开启权限。
			plus.device.setWakelock(true);
			// 版本更新方法
			APPUpdate();
			jpushModule.initJPushService();
			jpushModule.setLoggerEnable(true);
			this.getNotificationEnabled();
			jpushModule.setChannelAndSound({
				'channel':'',
				'channel_id': '',
			    'sound': "xindingdan"
			});
			//监听 极光推送连接状态
			jpushModule.addConnectEventListener((result) => {
				console.log('监听 极光推送连接状态', result);
				let connectEnable = result.connectEnable;
				uni.$emit('connectStatusChange', connectEnable);
			});
			//极光推送的消息通知回调
			jpushModule.addNotificationListener((result) => {
				var main = plus.android.runtimeMainActivity();
				var NotificationManager = plus.android.importClass('android.app.NotificationManager');
				var nm = main.getSystemService(plus.android.getAttribute(NotificationManager, "NOTIFICATION_SERVICE"));

				  // 获取角标数量
				var getAppBadgeCount = function() {
				    var badgeCount = 0;
				    if (nm && nm.getBadgeCount) { // 需要确保NotificationManager支持getBadgeCount方法
				      badgeCount = nm.getBadgeCount();
				    }
				    return badgeCount;
				};

				// 使用示例
				var badgeCount = getAppBadgeCount();
				console.log('当前角标数量: ' + badgeCount);
				jpushModule.setBadge(badgeCount + 1);
				plus.runtime.setBadgeNumber(badgeCount + 1);
				let notificationEventType = result.notificationEventType;
				// let woopId = result.extras && result.extras.dataType === 'woop' && result.extras.value;
				console.log('通知', result, notificationEventType);
				// 点击事件
				if (notificationEventType == 'notificationOpened') {
					uni.reLaunch({
						url: '/pages/index/index'
					})
					plus.push.clear()  //清除桌面角标
				}
			});
			uni.$on('connectStatusChange', (connectStatus) => {
				var connectStr = '';
				if (connectStatus == true) {
					connectStr = '已连接';
					this.getRegistrationID();
				} else {
					connectStr = '未连接';
				}
				console.log('监听到了连接状态变化 --- ', connectStr);
			});

			// #endif
			uni.getSystemInfo({
				success: function(e) {
					// #ifndef MP
					Vue.prototype.StatusBar = e.statusBarHeight;
					if (e.platform == 'android') {
						Vue.prototype.CustomBar = e.statusBarHeight + 50;
					} else {
						Vue.prototype.CustomBar = e.statusBarHeight + 45;
					};
					// #endif

					// #ifdef MP-WEIXIN
					Vue.prototype.StatusBar = e.statusBarHeight;
					let custom = wx.getMenuButtonBoundingClientRect();
					Vue.prototype.Custom = custom;
					Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
					// #endif

					// #ifdef MP-ALIPAY
					Vue.prototype.StatusBar = e.statusBarHeight;
					Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
					// #endif
				}
			})

            // 启动30秒定时器
            this.globalTimer = setInterval(() => {
                let isLogin = uni.getStorageSync('isLogin')
                if(isLogin){
                    this.getLocation();
                }
            }, 30000);
		},
		onShow: function() {

		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
            getLocation() {
                // clearLocations;
                getLocations;
                startServe;
                let thiss = this;
                let a = function(){
                    console.log('发送请求');
                    let res = JSON.parse(uni.getStorageSync('LIn97112479'));
                    let latitude = res.coords.latitude;
                    let longitude = res.coords.longitude;

                    uni.setStorageSync('latitude',res.coords.latitude);
                    uni.setStorageSync('longitude',res.coords.longitude);

                    thiss.globalajax('user/modify', {
                        lat: uni.getStorageSync('latitude'),
                        lng: uni.getStorageSync('longitude'),
                    }, 'POST', function(res) {
                        console.log(res);
                        uni.hideLoading()
                        if (res.data.code == 200) {
                            // console.log('向后台发送位置了')
                        } else {
                            /*a.$showModal({
                                title:'友情提示',
                                content:res.data.msg,
                                showCancel:false,
                                confirmText:'我知道了',
                                success: (res) => {
                                }
                            });*/
                        }
                    });
                }
                let b = function(err){
                    console.log('报错提醒',err);
                    uni.showModal({
                        title:'提示',
                        content:JSON.stringify(err)
                    })
                }
                getLocations({provider:"amap",geocode:true,fun:a,err:b,time:10000})
                /*let that = this;
                setBattery()
                startServe()
                const _locationChangeFn = function(res) {
                    console.log(22222);
                    console.log(res.latitude, res.longitude);
                    uni.setStorage({
                        key: 'mylocation',
                        data: res
                    })
                    if (that.isLogin) {
                        console.log(res.latitude, res.longitude);
                        // that.sendLocation(res.latitude, res.longitude)
                    }
                }

                let a = function(){
                    console.log('发送请求');
                    console.log(uni.getStorageSync('LIn97112479'));
                    var temp_data_new = JSON.parse(uni.getStorageSync('LIn97112479'))
                    const currentLocation = {
                        latitude: temp_data_new.coords.latitude,
                        longitude: temp_data_new.coords.longitude
                    };
                    _locationChangeFn(currentLocation);

                }
                let b = function(err){
                    console.log('报错提醒',err);
                    // a.$showModal({
                    // 	title:'友情提示',
                    // 	content:JSON.stringify(err),
                    // 	showCancel:false,
                    // 	confirmText:'我知道了',
                    // 	success: (res) => {
                    // 	}
                    // });
                }
                getLocations({provider:"amap",geocode:true,fun:a,err:b,time:1000})
                // https://ext.dcloud.net.cn/plugin?id=18448   插件地址*/
            },
			getRegistrationID() {
				jpushModule.getRegistrationID((result) => {
					let registerID = result.registerID;
					console.log('获取registerID', registerID);
					uni.setStorageSync('registerID', registerID);
				});
			},
			getNotificationEnabled() {
				if (uni.getSystemInfoSync().platform == 'ios') {
					jpushModule.requestNotificationAuthorization((result) => {
						let status = result.status;
						if (status < 2) {
							this.noticMsgTool();
						}
					});
				} else {
					jpushModule.isNotificationEnabled((result) => {
						console.log('判断android是否打开权限1:true,0:false', result);
						if (result.code == 0) {
							//如果为0则表示 未打开通知权限
							this.noticMsgTool();
						}
					});
				}
			},
			noticMsgTool() {
				if (uni.getSystemInfoSync().platform == 'ios') {
					//苹果打开对应的通知栏
					uni.showModal({
						title: '通知权限开启提醒',
						content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
						showCancel: false,
						confirmText: '去设置',
						success: function(res) {
							if (res.confirm) {
								var app = plus.ios.invoke('UIApplication', 'sharedApplication');
								var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
								plus.ios.invoke(app, 'openURL:', setting);
								plus.ios.deleteObject(setting);
								plus.ios.deleteObject(app);
							}
						}
					});
				} else {
					//android打开对应的通知栏
					var main = plus.android.runtimeMainActivity();
					var pkName = main.getPackageName();
					var uid = main.getApplicationInfo().plusGetAttribute('uid');
					uni.showModal({
						title: '通知权限开启提醒',
						content: '您还没有开启通知权限，无法接受到消息通知，请前往设置',
						showCancel: false,
						confirmText: '去设置',
						success: function(res) {
							if (res.confirm) {
								var Intent = plus.android.importClass('android.content.Intent');
								var Build = plus.android.importClass('android.os.Build');
								//android 8.0引导
								if (Build.VERSION.SDK_INT >= 26) {
									var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
									intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
								} else if (Build.VERSION.SDK_INT >= 21) {
									//android 5.0-7.0
									var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
									intent.putExtra('app_package', pkName);
									intent.putExtra('app_uid', uid);
								} else {
									//(<21)其他--跳转到该应用管理的详情页
									intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
									var uri = Uri.fromParts('package', mainActivity.getPackageName(), null);
									intent.setData(uri);
								}
								// 跳转到该应用的系统通知设置页
								main.startActivity(intent);
							}
						}
					});
				}
			},
		}
	}
</script>

<style lang="scss">
    @import "@/uni_modules/uview-ui/index.scss";
	/*每个页面公共css */
	.hover_class{
		opacity: 0.7;
	}
	.page_height_box{
		height: 100vh;
	}
	.page_tip{
		width: 100%;
		padding: 20rpx 0;
		text-align: center;
		color: #C0C0C0;
		font-size: 22rpx;
		padding-bottom: 40rpx;
	}
	.null_box{
        text-align: center;
		image{
			width: 300rpx;
			margin: 0 auto;
			display: block;
		}
		.null_tip{
			text-align: center;
			// padding-top: 20rpx;
			margin-top: 30rpx;
			color: #606266;
			font-size: 28rpx;
		}
		.null_btn{
			width: 320rpx;
			height: 66rpx;
			text-align: center;
			line-height: 66rpx;
			color: #fff;
			margin: 0 auto;
			border-radius: 200rpx;
			background-color: #418AFF;
			margin-top: 30rpx;
			font-size: 30rpx;
		}
	}
</style>
